package com.xinqi.modules.chat.third.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Objects;

/**
 * @version V1.0
 * @Title: 群头像生成工具类
 * @ClassName: com.xinqi.modules.chat.third.utils.ImageUtil.java
 * @Description:
 * @Copyright 星齐科技（云南）有限公司 - Powered By 技术部
 * @author: yyzhen
 * @date: 2023/8/21 9:45
 */
@Slf4j
public final class ImageUtil {

    private final static String FORMAT = "png";

    /**
     * 外部头像宽度
     */
    private final static int EXTERNAL_WIDTH = 220;

    /**
     * 外部头像高度
     */
    private final static int EXTERNAL_HEIGHT = 220;

    /**
     * 内部头像宽度
     */
    private final static int INSIDE_WIDTH = 140;

    /**
     * 内部头像高度
     */
    private final static int INSIDE_HEIGHT = 140;

    /**
     * 群头像的需求是仅两个成员的头像叠加。左下/右上
     *
     * @param img1
     * @param img2
     * @param fileName
     * @return
     */
    public static String composite2(String img1, String img2, String fileName, String defaultAvatar) {
        if (StringUtils.isEmpty(img1)) {
            return StringUtils.isEmpty(img2) ? defaultAvatar : img2;
        }
        if (StringUtils.isEmpty(img2)) {
            return StringUtils.isEmpty(img1) ? defaultAvatar : img1;
        }
        BufferedImage bufferedImage1 = cutHeadImages(img1, defaultAvatar);
        BufferedImage bufferedImage2 = cutHeadImages(img2, defaultAvatar);

        BufferedImage outImage = new BufferedImage(EXTERNAL_WIDTH, EXTERNAL_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D gra = outImage.createGraphics();
        outImage = gra.getDeviceConfiguration().createCompatibleImage(EXTERNAL_WIDTH, EXTERNAL_HEIGHT, Transparency.TRANSLUCENT);
        gra = outImage.createGraphics();
        gra.setBackground(null);
        //设置背景
        gra.setColor(new Color(0, 0, 0));
        gra.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));
        //填满图片
        gra.fillRect(0, 0, EXTERNAL_WIDTH, EXTERNAL_HEIGHT);
        outImage = gra.getDeviceConfiguration().createCompatibleImage(EXTERNAL_WIDTH, EXTERNAL_HEIGHT, Transparency.TRANSLUCENT);
        gra = outImage.createGraphics();
        //左下
        gra.drawImage(bufferedImage2, 15, 70, INSIDE_WIDTH, INSIDE_HEIGHT, null);
        //右上
        gra.drawImage(bufferedImage1, 65, 10, INSIDE_WIDTH, INSIDE_HEIGHT, null);

        return OssUtils.ossUploadInputStream(fileName + "." + FORMAT, getImageStream(outImage));
    }

    /**
     * 图片转化为圆形
     *
     * @param headUrl
     * @return
     */
    public static BufferedImage cutHeadImages(String headUrl, String defaultAvatar) {
        BufferedImage avatarImage = null;
        try {
            avatarImage = getBufferedImage(headUrl, defaultAvatar);
            if (Objects.isNull(avatarImage)) {
                return avatarImage;
            }
            //写一个新的图片缓存  并把原图片放入 最后一个参数使背景为透明的 即使边缘四个角为透明的
            BufferedImage rotundity = new BufferedImage(avatarImage.getWidth(), avatarImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
            //指定了一个圆   就是画了一个圆
            Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, avatarImage.getWidth(), avatarImage.getHeight());
            //将当前剪辑区域设置为任意剪辑形状。  这里是按之前的椭圆尺寸裁剪的
            Graphics2D g2 = rotundity.createGraphics();
            g2.setClip(shape);
            g2.setBackground(null);
            //抗锯齿
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, (RenderingHints.VALUE_TEXT_ANTIALIAS_GASP));
            g2.drawImage(avatarImage, 0, 0, null);
            g2.dispose(); //释放资源
            return rotundity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static BufferedImage getBufferedImage(String picPath, String defaultAvatar) {
        try {
            /**
             * ImageIO.getReaderFormatNames();
             * 得到 ImageIo　可以读取图片的格式　：
             * [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
             */
            BufferedImage imageBuff;
            if (picPath.indexOf("https://") == 0 || picPath.indexOf("http://") == 0) { //简单判断是网络图片还是本地图片
                imageBuff = ImageIO.read(new URL(picPath));
            } else {
                imageBuff = ImageIO.read(new File(picPath));
            }
            if (Objects.isNull(imageBuff)) {
                imageBuff = ImageIO.read(new URL(defaultAvatar));
            }
            return imageBuff;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InputStream getImageStream(BufferedImage bufferedImage) {
        InputStream is = null;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imOut;
        try {
            imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(bufferedImage, FORMAT, imOut);
            is = new ByteArrayInputStream(bs.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

}

